import React from 'react';
import './employeeManage.less';
import {browserHistory} from 'react-router';
import { Button, Table, Modal, Pagination, Form, message,Input,Select,Tree} from 'antd';
import $ from 'jquery';
import config from '../../../config/config';
const InputGroup = Input.Group;
const allRouter=config.router;
const Option = Select.Option;
const TreeNode = Tree.TreeNode;
const privilegeData=config.gData;
const token = sessionStorage.getItem('token');
class EmployeeManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employeeList:[],//员工列表
            allList:[],//所有员工列表
            Inkey:undefined,// 关键字
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            employeeCount:0,//员工总数
            roleList:[],//角色列表
            visible3:false,//增加权限模态框
            privilegeNameList:[],//所有权限
            selectedPrivilegeList:[],//已选择的权限列表把初始值赋值一份给保存
            initialPrivilegeList:[],//保存最开始的已关联权限列表的初始值，如果模态框点击取消则不改变，如果点击确定，再把数据赋值
            tree1: { name: '全部权限', keyword: '根' },
            checkedKeys1:[],//树形选择
            privilegeOfRole:[],//用来过滤该角色没有的权限
            choseId:'',//修改权限时选择的Id
            roleTeam:undefined,
            dedicateList:[],//角色已失效列表
            choseRole:'',//每次编辑权限所选择的角色ID
        }
    }
    componentDidMount() {
        //获取员工列表
        this.getEmployeeList();
        //获取角色列表
        this.getRolesList();
        //所有权限数据
        this.setState({
            privilegeNameList:privilegeData
        })
    }
    //获取角色列表  只是为了显示角色
    getRolesList() {
        let url=allRouter.patientOrigin+'/role/list';
        if(!this.state.Inkey){
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:res=>{
                    let roles=[];
                    const rolesList = res.roles;
                    const dedicateList=[];
                    console.log(rolesList);
                    if (rolesList.length > 0) {
                        rolesList.forEach((ele, i) => {
                            if(ele.state==='禁用'){
                                dedicateList.push(ele.name);
                            }
                            roles.push({ value: ele.name, label: ele.name,index:ele._id,tree:ele.tree});

                        });
                    }
                    console.log(roles);
                    this.setState({
                        roleList:roles,
                        dedicateList,
                    })
                },
                error:err=>{
                    message.config({ top: 80, });
                    message.error('获取员工角色列表失败，请返回重新操作', 2);
                }
            });
        }
    }
    //获取员工列表
    getEmployeeList() {
        let url=allRouter.patientOrigin+'/doctor/list';
        $.ajax({
            url:url,
            type: "get",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    //给列表每一项增加索引
                    if (data.users.length > 0) {
                        data.users.forEach((ele, i) =>{
                            ele.index= i + 1;
                        });
                    }
                    console.log(data);
                    this.setState({
                       employeeList:data.users,
                        allList:data.users
                    })
                }else{
                    console.log("获取员工列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //搜索关键字
    changeInkey(e) {
        this.setState({
            Inkey: e.target.value
        })
    }
    //搜索
    searchRoles(e) {
        let value = e.target.value || this.state.Inkey;
        // console.log(value);
        let employeeList = [];
        let employeeList1 = [];
        this.state.allList.forEach(item=>{
            if(value){
                if(item.name.includes(value)||item.phone.includes(value)){
                    employeeList1.push(item);
                }
            }else{
                employeeList1.push(item);
            }
        });
        if(this.state.roleTeam!=="allRole"){
            employeeList1.forEach(item=>{
                //console.log(item.role);
                if(this.state.roleTeam){
                    if(item.role===this.state.roleTeam){
                        employeeList.push(item);
                    }
                }else{
                    employeeList.push(item);
                }
            });
        }else{
            employeeList=employeeList1;
        }
        employeeList.sort((a,b)=>a.index-b.index);
        this.setState({employeeList});
    }

    //选择角色组时候的搜索
    handleChangeRole(value){
        this.setState({
            roleTeam:value,
        });
        // console.log(value);
        let employeeList1 = [];
        if(this.state.Inkey){
            this.state.allList.forEach(item=>{
                if(item.name.includes(this.state.Inkey)||item.phone.includes(this.state.Inkey)){
                    employeeList1.push(item);
                }
            });
        }else{
            employeeList1=this.state.allList;
        }
        if(value==="allRole"){
            this.setState({
                employeeList:employeeList1,
            });
            return;
        }
        let employeeList = [];
        employeeList1.forEach(item=>{
            //console.log(item.role);
            if(item.role===value){
                employeeList.push(item);
            }
        });
        employeeList.sort((a,b)=>a.index-b.index);
        this.setState({employeeList});

    }
    //分页
    changePage(pageindex) {
        this.setState({
            pageindex
        });
    }
    //删除人员数据
    deleteDepartment(recode) {
        // Modal.confirm({
        //     title: '删除人员',
        //     content: '确认删除该人员吗?',
        //     cancelText:'取消',
        //     okText:'确定',
        //     onCancel: () => { message.info('取消删除该人员') },
        //     onOk: () => {
        //         let url=allRouter.patientOrigin+'/doctor/delete';
        //         $.ajax({
        //             url:url,
        //             type: "POST",
        //             async: true,
        //             headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
        //             data:{
        //                 id:recode._id,
        //             },
        //             success:data=>{
        //                 if(data.code===200){
        //                     message.success('删除成功！', 2);
        //                     this.getEmployeeList();
        //                 }else{
        //                     message.info('删除失败,请重新操作');
        //                 }
        //             },
        //             error:err=>{
        //                 console.log(err);
        //             }
        //         });
        //     }
        // })
    }
    //编辑人员状态
    changeEmployeeState(recode){
        //真正修改人员状态
        let role='';
        this.state.roleList.map(item=>{
            if(recode.role===item.value){
                role=item.index;
            }
        });
        let that=this;
        let actualUpdateState=()=>{
            let url=allRouter.patientOrigin+'/doctor/update';
            $.ajax({
                url:url,
                type: "POST",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data:{
                    id:recode._id,
                    state:currentState,
                    role:role,
                },
                success:data=>{
                    if(data.code===200){
                        that.getEmployeeList();
                    }else{
                        message.info('更改状态错误');
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        };

        let currentState=recode.state;
        if(currentState==="启用"){
            currentState="禁用";
            let confirmString=<span style={{color:'red'}}>谨慎操作！若成功禁止，员工不得登入该门店后台！！</span>;
            Modal.confirm({
                title: '禁用人员',
                content: confirmString,
                onCancel:()=>{},
                onOk: () => {
                    actualUpdateState();
                }
            })
        }else if(currentState==="禁用"){
            currentState="启用";
            actualUpdateState();
        }
    }

    //权限管理人员信息.显示模态框
    editEmployeePrivilege(record) {
        console.log(record.jurisdiction);
        this.setState({
            visible3: true,
            choseId:record._id,
            selectedPrivilegeList:[],
            checkedKeys1:record.jurisdiction,
        });
        //  console.log(record.role);
        console.log('hjdfhjfjhf');
        console.log(this.state.roleList);
        this.state.roleList.map(item=>{
            if(item.label===record.role){
                this.setState({
                    privilegeOfRole:item.tree,
                    choseRole:item.index,
                })
            }
        })
    }
    //权限模态框确定
    handleOk3() {
        Modal.confirm({
            title: '修改员工权限',
            className:'confirm-error',
            content: '操作提醒！修改之后该员工可能需要重新登录。',
            onCancel: () => { },
            onOk: () => {
                this.setState({
                    visible3: false,
                    selectedPrivilegeList:this.state.checkedKeys1
                },()=>{
                    //console.log('打印在选择的时候改变的数组');
                    // console.log(this.state.selectedPrivilegeList);
                    let url=allRouter.patientOrigin+'/doctor/update';
                    $.ajax({
                        url: url,
                        type: "post",
                        async: true,
                        traditional: true,
                        headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                        data: {
                            id:this.state.choseId,
                            role:this.state.choseRole,
                            jurisdiction:this.state.selectedPrivilegeList,//权限
                        },
                        success:data => {
                            console.log(data);
                            if(data.code===200){
                                message.info('权限修改成功',);
                                this.getEmployeeList();

                            }else{
                                message.info('权限修改失败,请重新操作');
                            }
                        },
                        error:err=>{
                            console.log(err);
                        }
                    });
                    this.getEmployeeList();
                })
            }
        });

    }
    //取消权限模态框
    handleCancel3() {
        this.setState({
            visible3: false,
            selectedPrivilegeList:this.state.initialPrivilegeList
        });
    }
    //tree树形变化函数
    onCheckPrivilege1(checkedKeys1, e) {
        //console.log(checkedKeys1);
        this.setState({
            checkedKeys1,
        });
    }
    render(){
        const loop1 = data =>
            data.map((item) => {
                if (item.son.length) {
                    return (
                        <TreeNode key={item.keyword} title={item.name}>
                            {loop1(item.son)}
                        </TreeNode>
                    );
                }else{
                    return <TreeNode key={item.keyword} title={item.name} className='finalNode' disabled={this.state.privilegeOfRole.indexOf(item.keyword)===-1?true:false}/>;
                }
            });
        const treeNodes1 = loop1(this.state.privilegeNameList);
        //分页
        let index = this.state.pageindex;
        let size = this.state.pagesize;
        const data = this.state.employeeList.slice(size*(index-1),size*index);
        const columns = [
            {
                title: '序号',
                dataIndex: 'index',
                width: 50,
            },
            {
                title: '人员姓名',
                dataIndex: 'name',
                width: 100,
            }, {
                title: '手机号',
                dataIndex: 'phone',
                width: 100,
            },{
                title: '所属角色组',
                dataIndex: 'role',
                width: 100,
                render:text=><span style={{color:this.state.dedicateList.indexOf(text)===-1?'':'red'}}>{this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text}</span>
            },
            {
                title: '所属科室',
                dataIndex: 'department',
                width: 200,
                render: text => <span>{text.filter(key => key !=null ).length === 0 ? "——" : text.filter(key => key !=null ).length === 1 ? text.filter(key => key !=null )[0].name : text.filter(key => key !=null )[0].name+'等'+text.length+'个科室'}</span>
            }, {
                title: '所属诊所',
                dataIndex: 'shop',
                width: 200,
                render: text => <span>{text?text.length?text.filter(key=>key!=null).length === 0 ? "——" : text.filter(key=>key!=null).length === 1 ? text.filter(key=>key!=null)[0].name : text.filter(key=>key!=null)[0].name+'等'+text.filter(key=>key!=null).length+'个诊所':'':''}</span>
            }, {
                title: '岗位属性',
                dataIndex: 'post',
                width: 80,
            }, {
                title: '状态',
                dataIndex: 'state',
                width: 50,
                render:(text,record)=>{ return <Button disabled={record.role==="超级管理员"} type={record.state==='启用'?'primary':'danger'} onClick={this.changeEmployeeState.bind(this,record)}>{record.state==='启用'?'已启用，点击禁用':'已禁用，点击启用'}</Button>}
            }, {
                title: '权限管理',
                width: 100,
                render: (text, record) => (
                    <div>
                        <Button disabled={record.role==="超级管理员"} onClick={this.editEmployeePrivilege.bind(this, record)}  >分配权限</Button>
                    </div>
                )
            },{
                title: '操作',
                width: 100,
                render: (text, record) => (
                    <div>
                        <Button disabled={record.role==="超级管理员"} onClick={()=>{browserHistory.push('addEmployeeForm/'+record._id)}}>编辑</Button>
                        {/*<Button onClick={this.deleteDepartment.bind(this, record)}  type="danger">删除</Button>*/}
                    </div>
                )
            }
        ];
        return (
            <div className="container">
                <div className="store-manage-content my-clear-fix">
                    <div className="my-clear-fix">
                        {/*增加按钮*/}
                        <div className="storeAdd employee-manage-add">
                            <Button onClick={() => { browserHistory.push('addEmployeeForm/0') }} type="primary">
                                <img src={require('../../../../images/add.png')} alt=""/>
                                新增人员</Button>
                        </div>
                        <div className='role-manage-box-search my-clear-fix employee-manage-box-search'>
                            <div className='addetd-z employee-manage-search'>
                                <InputGroup compact>
                                    <Select  onChange={this.handleChangeRole.bind(this)} style={{width:'200px'}} placeholder="请选择角色组">
                                        <Option value='allRole' >所有角色</Option>
                                        {this.state.roleList.map(item=>{
                                            return (
                                                <Option value={item.label} key={item.index} >{item.label}</Option>
                                            )
                                        })}
                                    </Select>
                                    <Input
                                        placeholder="请输入姓名或手机号"
                                        value={this.state.Inkey}
                                        onChange={(e) => this.changeInkey(e)}
                                        onPressEnter={(e)=>this.searchRoles(e)}
                                    />
                                </InputGroup>
                            </div>
                            <div className="role-manage-right">
                                <Button type="primary" className='member-button' icon="search" onClick={this.searchRoles.bind(this)}>搜索</Button>
                            </div>
                        </div>
                    </div>
                    {/*医生挂号费列表 */}
                    <div className='all-roles-table'>
                        <Table
                            rowKey="index"
                            columns={columns}
                            dataSource={data}
                            pagination={false}
                            bordered
                        />
                    </div>
                    {/*分页*/}
                    <div className="pagination">
                        <Pagination  showQuickJumper current={this.state.pageindex} total={this.state.employeeList.length || 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                    </div>

                    {/*关联权限*/}
                    <Modal footer={false}
                           title={this.state.modalType == 'add' ? '添加' : '编辑'}
                           visible={this.state.visible3}
                           onOk={this.handleOk3.bind(this)}
                           onCancel={this.handleCancel3.bind(this)}
                           className="large-model"
                    >
                        <Tree
                            checkable
                            defaultExpandAll
                            onCheck={this.onCheckPrivilege1.bind(this)}
                            checkedKeys={this.state.checkedKeys1}
                            className='privilegeTree'
                        >
                            <TreeNode key={this.state.tree1.keyword} title={this.state.tree1.name}>
                                {treeNodes1}
                            </TreeNode>
                        </Tree>
                        <p style={{ marginTop: 30 ,textAlign:'right'}}>
                            <Button className='member-button-aa' onClick={this.handleOk3.bind(this)} style={{ width: 100 }} type='primary'>确定</Button>
                            <Button className='member-button-aa' onClick={this.handleCancel3.bind(this)} style={{ width: 100, marginLeft: 30 }} >取消</Button>
                        </p>
                    </Modal>
                </div>
            </div>
        )
    }
}
export default EmployeeManage;